package com.loe.ui.view

import android.content.Context
import android.os.Build
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import android.widget.LinearLayout
import androidx.annotation.Keep
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.loe.logger.LoeLogger
import com.loe.mvp.ext_java.delay
import com.loe.ui.*
import com.loe.ui.api.IUiView
import com.loe.ui.api.IUiViewGroup
import com.loe.ui.api.ViewPagerApi
import com.loe.ui.page.UiPage
import com.loe.ui.view_other.UiTabView
import com.quickjs.JSObject

@Keep
open class UiViewPager : ViewPager, IUiViewGroup
{
    constructor(context: Context) : super(context)
    {
        init()
    }

    fun init()
    {
        adapter = viewAdapter
        addOnPageChangeListener(object : ViewPager.OnPageChangeListener
        {
            override fun onPageScrolled(i: Int, positionOffset: Float, positionOffsetPixels: Int)
            {
                if(line != null)
                {
                    var scale = positionOffset
                    ////////////////////////////// 毛毛虫模式 ///////////////////////////////
                    if(tabView!!.tabLineSticky)
                    {
                        if (scale > 0.5)
                        {
                            if (W != 0) params?.width = (W * tabView!!.tabLineRate + W * (1 - scale) * 2).toInt()
                            scale = (scale - 0.5f) * 2
                        } else
                        {
                            if (W != 0) params?.width = (W * tabView!!.tabLineRate + W * scale * 2).toInt()
                            scale = 0f
                        }
                    }
                    ////////////////////////////////////////////////////////////////////////
                    setPosition(((i + scale) * W).toInt())
                }
            }

            override fun onPageScrollStateChanged(state: Int)
            {
            }

            override fun onPageSelected(i: Int)
            {
                (viewList[i] as IUiView).onSelect?.invoke()
                tabView?.select(i, true)
            }
        })
    }

    override var uiPage: UiPage? = null

    override val jsObject by lazy { ViewPagerApi(this).jsObject }

    override fun setUI(ui: JSObject, uiPage: UiPage?): View
    {
        this.uiPage = uiPage

        // click
        ui.gotHasBoolean("isClick") { setClick(it) }

        // 递归子元素
        ui.gotHasArray("childs")
        { childs ->
            childs.forEach<JSObject>
            {
                uiPage?.createUI(it)?.let()
                { view ->
                    viewList.add(view)
                }
            }
            viewAdapter.notifyDataSetChanged()
        }

        // isSmoothScroll
        ui.gotHasBoolean("isSmoothScroll") { isSmoothScroll = it }

        // select
        ui.gotHasInt("select")
        {
            currentItem = it
        }

        // 添加tabId
        ui.gotHasString("tabId")
        {
            delay()
            {
                uiPage?.findView<UiTabView>(it)?.let { initTab(it) }
            }
        }

        return this
    }

    override var onSelect: (() -> Unit)? = null

    /** viewPager列表 */
    val viewList = ArrayList<View>()

    /** viewPager适配器 */
    val viewAdapter = object : PagerAdapter()
    {
        override fun getCount(): Int = viewList.size

        override fun isViewFromObject(view: View, o: Any): Boolean = view == o

        override fun destroyItem(container: ViewGroup, i: Int, o: Any)
        {
            container.removeView(o as View)
        }

        override fun instantiateItem(container: ViewGroup, i: Int): Any
        {
            val view = viewList[i]
            container.addView(view)
            return view
        }
    }

    /********************************************** 点击 ****************************************/

    fun setClick(isClick: Boolean)
    {
        isAlpha = isClick
        isClickable = isClick
    }

    private var isAlpha = false

    override fun dispatchSetPressed(pressed: Boolean)
    {
        if (isAlpha) alpha = if (pressed || !isEnabled) 0.75f else 1f
        super.dispatchSetPressed(pressed)
    }

    override fun setEnabled(enabled: Boolean)
    {
        if (isAlpha) alpha = if (enabled) 1f else 0.75f
        super.setEnabled(enabled)
    }

    /********************************************** tab ****************************************/

    private var line: View? = null
    private var params: LinearLayout.LayoutParams? = null
    private var W = 0
    private var delW = 0

    private var tabView: UiTabView? = null

    /** 是否有顺滑滑动动画 */
    var isSmoothScroll = true

    fun initTab(tabView: UiTabView)
    {
        this.tabView = tabView
        line = tabView.tabLine
        params = line?.layoutParams as LinearLayout.LayoutParams?
        line?.post()
        {
            W = line!!.width / viewList.size
            delW = (W * (1 - tabView.tabLineRate) / 2 + 0.5).toInt()
            params?.width = (W * tabView.tabLineRate).toInt()
            line?.layoutParams = params
            setPosition(currentItem * W)
        }

        tabView.onItemSelected =
            {
                setCurrentItem(it, isSmoothScroll)
            }
    }

    /**
     * 设置滑动位置
     */
    private fun setPosition(position: Int)
    {
        params?.setMargins(position + delW, 0, 0, 0)
        line?.layoutParams = params
    }
}